package com.zh.note.huawei.onehundred.找等值元素;

import java.util.*;

/**
 * @Author: zhanghuan
 * @date: 2023/8/5 20:16
 * @description: create it
 */
public class Main {
    public static void main(String[] args) {
        // Scanner sc = new Scanner(System.in);
        // int n = sc.nextInt();
        // int m = sc.nextInt();
        // int[][] matrix = new int[n][m];
        int[][] matrix = {{0, 3, 5, 4, 2}, {2, 5, 7, 8, 3}, {2, 5, 4, 2, 4}};
        int n = 3;
        int m = 5;
        // 保存每个元素的位置；key是当前元素值，value是他的坐标
        Map<Integer, List<int[]>> numMap = new HashMap<>();
        // 用来存储，计算过的元素，key是一个唯一表示，value是它的距离
        Map<String, Integer> usedMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // int num = sc.nextInt();
                // matrix[i][j] = num;
                int num = matrix[i][j];
                int[] pos = new int[]{i, j};
                List<int[]> tempList = numMap.getOrDefault(num, new ArrayList<>());
                tempList.add(pos);
                numMap.put(num, tempList);
            }

        }
        // 存储结果
        List<List<Integer>> resList = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            // 记录每一行的计算结果
            List<Integer> rowList = new ArrayList<>();
            for (int j = 0; j < m; j++) {
                int num = matrix[i][j];
                //获取num出现的位置
                List<int[]> posList = numMap.get(num);
                // 只出现了一次
                if (posList.size() == 1) {
                    rowList.add(-1);
                    continue;
                }
                // 不止出现一次，需要计算最小距离
                int minDistance = Integer.MAX_VALUE;
                for (int k = 0; k < posList.size(); k++) {
                    int[] pos = posList.get(k);
                    int row = pos[0];
                    int col = pos[1];
                    // 排除与当前遍历坐标一样的坐标
                    if (row == i && col == j) {
                        continue;
                    }
                    String key = row + "," + col + "," + i + "," + j;
                    if (usedMap.containsKey(key)) {
                        minDistance = Math.min(minDistance, usedMap.get(key));
                    } else {
                        int distance = Math.abs(i - row) + Math.abs(j - col);
                        usedMap.put(key, distance);
                        minDistance = Math.min(minDistance, distance);

                    }
                }
                rowList.add(minDistance);
            }
            resList.add(rowList);
        }
        System.out.println(resList);


    }
}
